<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('交易记录') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('交易日期')" prop="transactionDate">
        <DatePicker v-model="transactionDate" type="daterange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['transactionRecords:records:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t('新增') }}
        </el-button>
      </el-col>
      <el-button size="mini" @click="upload.open = true">{{ $t('导入') }}</el-button>
    </el-row>

    <!-- 导入窗口 -->
    <el-dialog :title="$t('导入')" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false">
      <div v-loading="upload.loading">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url+'?dealId=' + queryParams.dealId"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
            <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
              {{ $t('下载模板') }}
            </el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-table
      v-loading="loading"
      :data="dealSpoTransactionRecordsList"
      border
      :summary-method="getSummaries"
      show-summary
      tooltip-effect="darkTable"
    >
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('交易日期')" align="center" prop="transactionDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transactionDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('交易后剩余数量（股）')" align="center" prop="transactionAfterNumber" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.transactionAfterNumber) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('交易数量（股）')" align="center" prop="transactionNumber" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.transactionNumber) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('交易单价（元/股）')" align="center" prop="transactionPrice" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.transactionPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('交易金额（元）')" align="center" prop="transactionAmount" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.transactionAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('手续费（元）')" align="center" prop="commission" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.commission) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('印花税（元）')" align="center" prop="stampDuty" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.stampDuty) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('过户费（元）')" align="center" prop="transferFee" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.transferFee) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('资金收入金额（元）')" align="center" prop="incomeAmount" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.incomeAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('抵消成本（元）')" align="center" prop="offsetCosts" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.offsetCosts) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('抵消公允价值变动损益（元）')" align="center" prop="offsetLosses" width="200">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.offsetLosses) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('增值税及附加（元）')" align="center" prop="valueAddedTax" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.valueAddedTax) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('财务顾问费（元）')" align="center" prop="financialAdvisoryFees" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.financialAdvisoryFees) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('计入投资收益（元）')" align="center" prop="investIncome" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.investIncome) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('收益率（%）(财务口径)')" align="center" prop="yield" width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.yield* 100, '') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" fixed="right" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['transactionRecords:records:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}
          </el-button>
          <el-button
            v-hasPermi="['transactionRecords:records:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改定增项目-交易记录对话框 -->
    <el-dialog
      :title="$t(title)"
      :visible.sync="formOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <dealSpoTransactionRecordsForm ref="dealSpoTransactionRecordsForm" />
    </el-dialog>
  </div>
</template>

<script>
  import {
    listDealSpoTransactionRecords,
    delDealSpoTransactionRecords,
    exportDealSpoTransactionRecords, sumDealSpoTransactionRecords
  } from '@/api/deal/spo/transaction/dealSpoTransactionRecords'
  import dealSpoTransactionRecordsForm from './dealSpoTransactionRecordsForm.vue'
  import { getToken } from '@/utils/auth'

  export default {
    components: {
      dealSpoTransactionRecordsForm
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 定增项目-交易记录表格数据
        dealSpoTransactionRecordsList: [],
        // 弹出层标题
        title: '交易记录',
        // 是否显示弹出层
        formOpen: false,
        // 交易时间 参数
        transactionDate: [],
        // 查询参数
        queryParams: {
          dealId: this.$route.query.id,
          reductionId: undefined,
          transactionAfterNumber: undefined,
          transactionNumber: undefined,
          transactionPrice: undefined,
          transactionAmount: undefined,
          commission: undefined,
          stampDuty: undefined,
          transferFee: undefined,
          incomeAmount: undefined,
          offsetCosts: undefined,
          offsetLosses: undefined,
          valueAddedTax: undefined,
          financialAdvisoryFees: undefined,
          investIncome: undefined,
          yield: undefined,
          createdBy: undefined,
          createdTime: undefined,
          updatedTime: undefined,
          startDate: undefined,
          endDate: undefined,
          pageNum: 1,
          pageSize: 10
        },
        // 导入参数
        upload: {
          // 是否显示弹出层（项目导入）
          open: false,
          // 弹出层标题（项目导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/records/dealSpoTransactionRecords/importData',
          // 遮罩层
          loading: false
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        sumData: {}
      }
    },
    created() {
      this.getList()
      this.calcSum()
    },
    methods: {
      /** 查询定增项目-交易记录列表 */
      getList() {
        this.loading = true
        if (this.transactionDate != null && this.transactionDate.length > 1) {
          this.queryParams.startDate = this.transactionDate[0]
          this.queryParams.endDate = this.transactionDate[1]
        } else {
          this.queryParams.startDate = undefined
          this.queryParams.endDate = undefined
        }
        listDealSpoTransactionRecords(this.queryParams).then(response => {
          this.dealSpoTransactionRecordsList = response.rows
          this.total = response.total
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
        this.calcSum()
      },
      calcSum() {
        sumDealSpoTransactionRecords(this.queryParams.dealId).then(res => {
          this.sumData = res.data
        })
      },
      getSummaries(param) {
        const { columns } = param
        const sums = []

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
          }
          if ((this.sumData && this.sumData[column.property]) || (this.sumData && this.sumData[column.property]) === 0) {
            sums[index] = this.moneyFormat(this.sumData[column.property], 2, true)
          }
        })

        return sums
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          dealId: undefined,
          reductionId: undefined,
          transactionDate: undefined,
          transactionAfterNumber: undefined,
          transactionNumber: undefined,
          transactionPrice: undefined,
          transactionAmount: undefined,
          commission: undefined,
          stampDuty: undefined,
          transferFee: undefined,
          incomeAmount: undefined,
          offsetCosts: undefined,
          offsetLosses: undefined,
          valueAddedTax: undefined,
          financialAdvisoryFees: undefined,
          investIncome: undefined,
          yield: undefined,
          createdBy: undefined,
          createdTime: undefined,
          updateBy: undefined,
          updatedTime: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.transactionDate = []
        this.resetForm('queryForm')
        this.queryHandle()
      },
      /** 新增按钮操作 */
      addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
          this.$refs.dealSpoTransactionRecordsForm.init(null)
        })
      },
      /** 修改按钮操作 */
      updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
          // 调用form页面的 init 方法初始化数据
          this.$refs.dealSpoTransactionRecordsForm.init(row)
        })
      },
      /** 删除按钮操作 */
      deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          return delDealSpoTransactionRecords(row.id)
        }).then(() => {
          this.getList()
          this.msgSuccess(this.$t('删除成功'))
        }).catch(() => {
          this.loading = false
        })
      },
      /** 导出按钮操作 */
      exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          return exportDealSpoTransactionRecords(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(() => {
        })
      },
      // 文件上传中处理
      handleFileUploadProgress() {
        this.upload.isUploading = true
        // this.upload.loading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response) {
        console.log(response)
        this.upload.open = false
        this.upload.isUploading = false
        // this.upload.loading = false
        this.$refs.upload.clearFiles()
        if (response.msg === 'success') {
          this.msgSuccess(this.$t('导入成功'))
        } else if (response.code === 500) {
          this.msgError(this.$t('数据异常'))
        } else {
          this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
        }
        this.getList()
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      // 文件达到上限处理
      handleFileExceed() {
        this.msgError(this.$t('可上传文件数量已达到上限'))
      },
      // 下载模板
      fetchTemplate() {
        var href1 = window.location.href
        var href2 = this.$route.path
        var url = href1.substring(0, href1.indexOf(href2)) + '/template/dealSpoTransactionRecordsTemplate.xlsx'
        var a = document.createElement('a')
        a.href = url
        a.download = '交易记录模板'
        a.click()
      },
      // 文件上传变更时间
      handleFileChange(file, fileList) {
        if (!(file.name.indexOf('xls') >= 0 && file.name.indexOf('xlsx') >= 0)) {
          this.msgError(this.$t('仅允许导入“xls”或“xlsx”格式文件！'))
          fileList.splice(0, 1)
        }
      }
    }
  }
</script>
